package com.gcloud.mesh.alert.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jeecg.common.exception.ParamException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gcloud.mesh.alert.dao.NotifyTemplateDao;
import com.gcloud.mesh.alert.entity.NotifyTemplateEntity;
import com.gcloud.mesh.header.exception.BaseException;
import com.gcloud.mesh.header.vo.alert.NotifyTemplateVo;

@Service
public class NotifyTemplateService {
	
	@Autowired
	NotifyTemplateDao templateDao;

	public NotifyTemplateVo getNotifyTemplate(String name, Map<String, String> params) throws BaseException {
		List<NotifyTemplateEntity> entities = this.templateDao.findByProperty("name", name);
		if (entities.isEmpty()) {
			throw new ParamException("::找不到通知模板");
		}
		return this.convertEntityToNotifyVo(entities.get(0), params == null ? new HashMap<String, String>() : params);
	}

	private NotifyTemplateVo convertEntityToNotifyVo(NotifyTemplateEntity entity, Map<String, String> params) {
		NotifyTemplateVo vo = new NotifyTemplateVo();
		vo.setName(entity.getName());
		vo.setTitle(this.convertWithParams(entity.getTitle(), params));
		vo.setContent(this.convertWithParams(entity.getContent(), params));
		return vo;
	}

	private String convertWithParams(String msg, Map<String, String> params) {
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if (entry.getKey() != null && entry.getValue() != null) {
				msg = msg.replace("${" + entry.getKey() + "}", entry.getValue());
			} 
		}
		return msg;
	}

	private NotifyTemplateVo convertEntityToRecoverVo(NotifyTemplateEntity entity, Map<String, String> params) {
		NotifyTemplateVo vo = new NotifyTemplateVo();
		vo.setName(entity.getName());
		vo.setTitle(this.convertWithParams(entity.getRecoverTitle(), params));
		vo.setContent(this.convertWithParams(entity.getRecoverContent(), params));
		return vo;
	}

	public NotifyTemplateVo getRecoverTemplate(String name, Map<String, String> params) throws BaseException {
		List<NotifyTemplateEntity> entities = this.templateDao.findByProperty("name", name);
		if (entities.isEmpty()) {
			throw new BaseException("cannot find the template");
		}
		return this.convertEntityToRecoverVo(entities.get(0), params == null ? new HashMap<String, String>() : params);
	}
}
